// pages/hospital-list/hospital-list.js
const app = getApp()

Page({
  data: {
    departmentId: null,
    searchKeyword: '',
    hospitalList: [],
    page: 1,
    pageSize: 10,
    isLoading: false,
    noMoreData: false
  },

  onLoad(options) {
    this.setData({ departmentId: options.departmentId })
    this.loadData(true)
  },

  // 加载数据
  async loadData(init = false) {
    if (this.data.noMoreData && !init) return

    try {
      const params = {
        page: init ? 1 : this.data.page,
        pageSize: this.data.pageSize,
        departmentId: this.data.departmentId,
        keyword: this.data.searchKeyword
      }
	  this.setData({ isLoading: true })

    var that = this
          	const { page, pageSize, searchKeyword } = this.data;
                app.util.request({
                        url: 'Hospital/listsbyid',
                        data: params,
                        complete(res) {
                                that.setData({
                                        noMoreData: res.data.data.hospital.length < pageSize
                                });
                        },
                        success(res) {
                                var data = res.data.data;
          					  console.log(data)
          					  var list = data.hospital
                                that.setData({
                                      hospitalList: init ? list : [...this.data.hospitalList, ...list],
                                      page: init ? 2 : page + 1,
          							isLoading: false
                                });
                        }
                })
    } catch (error) {
      this.setData({ isLoading: false })
      wx.showToast({ title: '加载失败', icon: 'none' })
    }
  },

  // 搜索输入
  onSearchInput: debounce(function(e) {
    this.setData({ searchKeyword: e.detail.value.trim() })
    this.loadData(true)
  }, 500),

  // 清空搜索
  clearSearch() {
    this.setData({ searchKeyword: '' })
    this.loadData(true)
  },

  // 加载更多
  loadMore() {
    if (!this.data.noMoreData) {
      this.loadData()
    }
  },

  // 跳转详情
  navigateToHospitalDetail(e) {
    const hospitalId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/vp_pz/pages/bdyl/hospital?id=${hospitalId}`
    })
  },
})

// 防抖函数
function debounce(fn, delay) {
  let timer = null
  return function(...args) {
    clearTimeout(timer)
    timer = setTimeout(() => fn.apply(this, args), delay)
  }
}